"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Compatibility
Case Name   : 不指定参数，部分测试点合理报错
Create At   : 2023/06/02
Owner       : n@ningyali
Description :
        1.建表
        2.导入数据，不指定任何参数，导入值不重复
        3.导入数据，导入值里含特殊符号
        4.导入数据，违反主键约束
        5.导入数据，唯一键值重复
        6.清理环境
Expect      :
        1.创建成功
        2.成功
        3.成功
        4.合理报错
        5.合理报错
        6.成功
History     :
"""
import os
import unittest

from yat.test import Node

from testcase.COMPATIBILITY.GRAMMAR.LOAD. \
    Opengauss_Compatibility_Grammar_Load_Common import LoadData
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class LoadData0033(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.common = Common()
        self.load_data = LoadData()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.case_lable = 'load_data_0033'
        self.db_name = f'db_{self.case_lable}'
        self.t_name = f't_{self.case_lable}'
        self.file_path = os.path.join('/home', self.pri_user.ssh_user)
        self.cols = 'c_id int primary key,c_card char(18) unique,' \
               'c_name nvarchar(200)'

        text1 = '----pre_step1：创建数据文件；expect:创建成功----'
        self.log.info(text1)
        self.data1 = "002	123456789987654322	xiaohuaer\n" \
                     "003	123456789987654323	小猪猪\n" \
                     "004	123456789987654324	小猪头"
        self.data2 = "002	123456789987654322	xia@#@#aer\n" \
                     "003	123456789987654323	小>:<猪\n" \
                     "004	123456789987654324	小*)*头"
        self.data3 = "002	123456789987654322	xiaohuaer\n" \
                     "002	123456789987654323	小猪猪"
        self.data4 = "002	123456789987654322	xiaohuaer\n" \
                     "003	123456789987654323	小猪猪\n" \
                     "004	123456789987654322	художников\n" \
                     "005	123456789	allin"
        res = self.load_data.create_data_file(self.pri_user, self.case_lable,
                                              self.data1, self.data2,
                                              self.data3, self.data4)
        self.assertTrue(res, '执行失败:' + text1)

        text2 = '----pre_step2：创建兼容B库；expect:创建成功----'
        self.log.info(text2)
        res = self.load_data.create_b_db(self.pri_sh, self.db_name)
        self.assertTrue(res, '执行失败:' + text2)

    def test_load(self):
        text = '----step1：建表；expect：建表成功----'
        self.log.info(text)
        res = self.load_data.create_table(self.pri_sh, self.db_name,
                                          self.t_name, self.cols)
        self.assertTrue(res, '执行失败:' + text)

        text = '----step2：导入数据，不指定任何参数，导入值不重复；expect：成功----'
        self.log.info(text)
        f_path1 = os.path.join(self.file_path, f'{self.case_lable}_1.txt')
        sql1 = f"load data infile '{f_path1}' " \
            f"into table {self.t_name};" \
            f"select * from {self.t_name};"
        res1 = self.pri_sh.execut_db_sql(sql1, dbname=self.db_name)
        self.log.info(res1)
        rows, _ = self.common.parse_sql_query_res(res1)
        expect = [['2', '123456789987654322', 'xiaohuaer'],
                  ['3', '123456789987654323', '小猪猪'],
                  ['4', '123456789987654324', '小猪头']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = '----step3：导入数据，导入数据含特殊符号；expect：成功----'
        self.log.info(text)
        f_path2 = os.path.join(self.file_path, f'{self.case_lable}_2.txt')
        sql2 = f'truncate table {self.t_name};' + \
               sql1.replace(f_path1, f_path2)
        res2 = self.pri_sh.execut_db_sql(sql2, dbname=self.db_name)
        self.log.info(res2)
        rows, _ = self.common.parse_sql_query_res(res2)
        expect = [['2', '123456789987654322', 'xia@#@#aer'],
                  ['3', '123456789987654323', '小>:<猪'],
                  ['4', '123456789987654324', '小*)*头']]
        self.assertEqual(rows, expect, '执行失败' + text)

        text = '----step4：导入数据，违反主键约束；expect：合理报错----'
        self.log.info(text)
        f_path3 = os.path.join(self.file_path, f'{self.case_lable}_3.txt')
        sql3 = sql2.replace(f_path2, f_path3)
        res3 = self.pri_sh.execut_db_sql(sql3, dbname=self.db_name)
        self.log.info(res3)
        einfo = 'ERROR:  duplicate key value violates unique constraint'
        self.assertIn(einfo, res3, '执行失败' + text)

        text = '----step5：导入数据，唯一键值重复；expect：合理报错----'
        self.log.info(text)
        f_path4 = os.path.join(self.file_path, f'{self.case_lable}_4.txt')
        sql4 = sql2.replace(f_path2, f_path4)
        res4 = self.pri_sh.execut_db_sql(sql4, dbname=self.db_name)
        self.log.info(res4)
        self.assertIn(einfo, res4, '执行失败' + text)

    def tearDown(self):
        self.log.info('----step6：清理环境；expect：清理成功----')
        res = self.load_data.clear_env(self.pri_sh, self.pri_user,
                                       self.db_name,
                                       os.path.join(self.file_path,
                                                    f"{self.case_lable}*"))
        self.assertTrue(res, '执行失败:清理环境')
        self.log.info(f'----{os.path.basename(__file__)} end----')
